<template>
  <div class="canvas-container">
    <canvas ref="canvasRef" id="canvas" width="1280" height="1040"></canvas>
    <!-- <div v-if="sceneStore.transition.active" class="scene-transition"></div> -->
  </div>
</template>

<script setup lang="ts">
import house from "@/assets/images/building/house.png";
import baseTiles from "@/assets/images/tiles/baseTiles.png";
import character from "@/assets/images/character/character.png";

import { loadMap } from "@/utils/map";
import { getScreenSize } from "@/utils";
import { renderMap } from "@/utils/map";
import type TiledMap from "tiled-types";
import { getCellPosition } from "@/utils";

import {
  setupKeyboardControls,
  initPlayerController,
} from "@/utils/playerController";
import { debounce } from "@/utils";
import { useMapStore } from "@/store/mapStore";
import { treeData } from "@/config/treeConfig";
import { useUserStore } from "@/store/userStore";
import { useTimeStore } from "@/store/timeStore";
import { treeManager } from "@/utils/treeManager";
import { onMounted, ref, watch, onUnmounted } from "vue";
import { furniturePlacer } from "@/utils/furnitureManager";
import { SceneType, useSceneStore } from "@/store/sceneStore";
import { useWeatherStore, WeatherType } from "@/store/weatherStore";

let isLoadingMap = false;
const mapStore = useMapStore();
const userStore = useUserStore();
const sceneStore = useSceneStore();
const weatherStore = useWeatherStore();
const screenSize = ref(getScreenSize());
const canvasRef = ref<HTMLCanvasElement>();

const handleResize = () => {
  if (!canvasRef.value) return;

  const tempCanvas = document.createElement("canvas");
  const tempCtx = tempCanvas.getContext("2d");
  tempCanvas.width = window.innerWidth;
  tempCanvas.height = window.innerHeight;

  if (tempCtx) {
    tempCtx.drawImage(canvasRef.value, 0, 0);
  }

  // 更新屏幕尺寸
  screenSize.value = getScreenSize();

  // 恢复画布内容
  if (tempCtx) {
    const ctx = canvasRef.value.getContext("2d");
    if (ctx) {
      ctx.imageSmoothingEnabled = false;
      ctx.drawImage(tempCanvas, 0, 0);
    }
  }
};

// 防抖处理窗口大小变化
const debouncedResize = debounce(handleResize, 100);

// 设置画布大小
const resizeCanvas = () => {
  if (!canvasRef.value) return;

  // 保存当前内容
  const tempCanvas = document.createElement("canvas");
  const tempCtx = tempCanvas.getContext("2d");
  tempCanvas.width = canvasRef.value.width;
  tempCanvas.height = canvasRef.value.height;

  if (tempCtx) {
    tempCtx.drawImage(canvasRef.value, 0, 0);
  }

  canvasRef.value.width = screenSize.value.width;
  canvasRef.value.height = screenSize.value.height;

  // 恢复内容并重新渲染
  const ctx = canvasRef.value.getContext("2d");
  if (ctx && tempCtx) {
    ctx.imageSmoothingEnabled = false; // 关闭图像平滑
    ctx.drawImage(tempCanvas, 0, 0);
  }

  requestAnimationFrame(() => {
    renderGame();
  });
};

let map: TiledMap | null = null;
let renderInProgress = false;

// 渲染游戏
const renderGame = async () => {
  if (!canvasRef.value || !map || renderInProgress) return;

  renderInProgress = true;

  const ctx = canvasRef.value.getContext("2d");
  if (!ctx) return;

  try {
    mapStore.currentCtx = ctx;
    await renderMap(ctx, map);
  } finally {
    renderInProgress = false;
  }
};

watch(
  () => screenSize.value,
  () => {
    resizeCanvas();
  },
  { deep: true }
);

// 检查玩家是否在传送点上
const checkSceneTransition = async () => {
  const portal = sceneStore.checkPortals();
  if (portal) {
    // 暂停定时器，防止多次触发
    clearInterval(sceneCheckInterval);
    await sceneStore.changeScene(portal.targetScene, portal.targetPosition);
    await loadCurrentSceneMap();
    await renderGame();
    sceneCheckInterval = setInterval(checkSceneTransition, 200);
  }
};

// 加载当前场景的地图
const loadCurrentSceneMap = async () => {
  if (isLoadingMap) {
    console.log("地图正在加载中，跳过重复加载");
    return;
  }
  isLoadingMap = true;

  try {
    let mapPath = "";
    let currentImgsMap: Record<number, string> = {};

    await treeManager.loadTreeSprites(
      "/src/assets/images/tiles/tree1_spring.png"
    );

    treeManager.setTreeVisibility(sceneStore.currentScene === SceneType.FARM);

    switch (sceneStore.currentScene) {
      case SceneType.FARM:
        mapPath = "/src/assets/maps/baseMap.json";
        currentImgsMap = {
          1: baseTiles,
          2: baseTiles,
          3: baseTiles,
          8: baseTiles,
          9: baseTiles,
          7: baseTiles,
          15: house,
        };
        break;
      case SceneType.HOUSE:
        mapPath = "/src/assets/maps/farmHouse.json";
        break;
      default:
        mapPath = "/src/assets/maps/baseMap.json";
        currentImgsMap = {
          1: baseTiles,
          2: baseTiles,
          3: baseTiles,
          8: baseTiles,
          9: baseTiles,
          7: baseTiles,
          15: house,
        };
    }

    map = await loadMap(mapPath);

    if (map && map.layers) {
      map.layers.forEach((layer) => {
        const layerId = layer.id;
        if (
          layerId !== undefined &&
          currentImgsMap[layerId as keyof typeof currentImgsMap]
        ) {
          (layer as any).image =
            currentImgsMap[layerId as keyof typeof currentImgsMap];
        }
      });
    }

    mapStore.updateMapData(map);
  } finally {
    isLoadingMap = false;
  }
};

let sceneCheckInterval: any = null;
let cleanupKeyboardControls: (() => void) | null = null;

onMounted(async () => {
  clearInterval(sceneCheckInterval);
  await loadCurrentSceneMap();

  cleanupKeyboardControls = setupKeyboardControls();

  const playerController = await initPlayerController(
    character,
    canvasRef.value
  );

  // 动态导入按需加载，加载已放置的家具
  // 只有当前这个模块加载完毕了，才会执行()里面的代码，避免循环依赖
  import("@/utils/furnitureManager").then(({ furniturePlacer }) => {
    furniturePlacer.loadPlacedFurniture();
  });

  userStore.setPlayerInstance(playerController);

  // 初始化天气效果
  weatherStore.initWeatherEffects();
  weatherStore.startWeatherEffect(WeatherType.RAIN, 1);
  weatherStore.updateWeatherForScene(sceneStore.currentScene);

  const timeStore = useTimeStore();

  if (sceneStore.currentScene === SceneType.FARM) {
    // 添加树木
    treeData.forEach((tree) => {
      treeManager.addTree({
        type: tree.type,
        stage: tree.stage,
        x: tree.x,
        y: tree.y,
        season: timeStore.gameTime.season,
        visible: true,
      });
    });
  }

  sceneCheckInterval = setInterval(checkSceneTransition, 200);

  window.addEventListener("resize", debouncedResize);

  window.addEventListener("click", (event) => {
    getCellPosition(event.clientX, event.clientY);
  });

  resizeCanvas();
});

onUnmounted(() => {
  // 移除窗口大小变化的监听器
  window.removeEventListener("resize", handleResize);
  clearInterval(sceneCheckInterval);

  if (cleanupKeyboardControls) {
    cleanupKeyboardControls();
  }
});
</script>

<style scoped lang="scss">
.canvas-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background: #000;
}

canvas {
  image-rendering: pixelated;
  image-rendering: crisp-edges;
  transform: translateZ(0); /* 启用硬件加速 */
  backface-visibility: hidden;
}

.scene-transition {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: black;
  opacity: 0.8;
  z-index: 100;
  animation: fade 1s ease-in-out;
}

@keyframes fade {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
</style>
